package com.xiaoxin.monitor.service;

import com.xiaoxin.common.core.utils.StrUtil;
import com.xiaoxin.monitor.constant.SmsContant;
import com.xiaoxin.monitor.function.Function;
import de.codecentric.boot.admin.server.domain.entities.Instance;
import de.codecentric.boot.admin.server.domain.entities.InstanceRepository;
import de.codecentric.boot.admin.server.domain.events.InstanceDeregisteredEvent;
import de.codecentric.boot.admin.server.domain.events.InstanceEvent;
import de.codecentric.boot.admin.server.domain.events.InstanceRegisteredEvent;
import de.codecentric.boot.admin.server.domain.events.InstanceStatusChangedEvent;
import de.codecentric.boot.admin.server.domain.values.Registration;
import de.codecentric.boot.admin.server.notify.AbstractEventNotifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.thymeleaf.util.MapUtils;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 通知发送配置
 *
 * @author ZhangXX
 * @date @2024/02/04 13:19
 */
@Component
public class StatusChangeNotifier extends AbstractEventNotifier {
    private static final Logger log = LoggerFactory.getLogger(StatusChangeNotifier.class);

    public StatusChangeNotifier(InstanceRepository repository) {
        super(repository);
    }


    private static final Map<Class<?>, Function<InstanceEvent, Instance, String>> cacheMap = new HashMap<>();

    static {
        //注册
        cacheMap.put(InstanceRegisteredEvent.class, StatusChangeNotifier::register);
        //注销
        cacheMap.put(InstanceDeregisteredEvent.class, StatusChangeNotifier::deRegistered);
        //状态变更
        cacheMap.put(InstanceStatusChangedEvent.class, StatusChangeNotifier::statusChanged);
    }


    @Override
    protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
        return Mono.fromRunnable(() -> {

            Function<InstanceEvent, Instance, String> messageBiFunction = cacheMap.get(event.getClass());
            if (messageBiFunction != null) {
                log.info("Instance Status Change: [{}]", messageBiFunction.apply(event, instance));
            }
        });
    }

    /**
     * 注册通知
     *
     * @param event
     * @param instance
     * @return
     */
    private static String register(InstanceEvent event, Instance instance) {
        Registration registration = instance.getRegistration();
        String registerMsg = StrUtil.replace(SmsContant.REGISTER, registration.getName(), registration.getServiceUrl());
        log.info("发送 服务上线 的通知！ {}", registerMsg);
        return registerMsg;
    }


    /**
     * 注销通知 服务离线
     *
     * @param event
     * @param instance
     * @return
     */
    private static String deRegistered(InstanceEvent event, Instance instance) {
        Registration registration = instance.getRegistration();
        String destroyMsg = StrUtil.replace(SmsContant.DESTROY, registration.getName(), registration.getServiceUrl());
        log.info("发送 服务下线 的通知！ {}", destroyMsg);
        return destroyMsg;
    }

    /**
     * 状态变更通知
     *
     * @param event
     * @param instance
     * @return
     */
    private static String statusChanged(InstanceEvent event, Instance instance) {
        // 健康状态
        String status = ((InstanceStatusChangedEvent) event).getStatusInfo().getStatus();
        // 服务名称
        String serviceName = instance.getRegistration().getName().toLowerCase();
        // 服务所在的服务器ip地址
        String serviceUrl = instance.getRegistration().getServiceUrl();

        switch (status) {
            // 健康检查没通过
            case "DOWN":
                String downMsg = StrUtil.replace(SmsContant.DOWN, serviceName, serviceUrl, getDownComponents(instance));
                log.info("发送 健康检查没通过 的通知！ {}", downMsg);
                return downMsg;
            // 服务宕机
            case "OFFLINE":
                String offlineMsg = StrUtil.replace(SmsContant.OFFLINE, serviceName, serviceUrl);
                log.info("发送 服务宕机 的通知！ {}", offlineMsg);
                return offlineMsg;
            // 服务健康
            case "UP":
                String upMsg = StrUtil.replace(SmsContant.UP, serviceName, serviceUrl);
                log.info("发送 服务健康 的通知！ {}", upMsg);
                return upMsg;
            // 服务未知异常
            case "UNKNOWN":
                String unknownMsg = StrUtil.replace(SmsContant.UNKNOWN, serviceName, serviceUrl);
                log.info("发送 服务未知异常 的通知！ {}", unknownMsg);
                return unknownMsg;
            default:
                return "";
        }
    }

    /**
     * 获取不可用的组件
     *
     * @param instance
     * @return
     */
    private static String getDownComponents(Instance instance) {
        // 健康状态的详情
        //String details = JSONObject.toJSONString(instance.getStatusInfo().getDetails());
        List<String> downComponents = new ArrayList<>();
        Map<String, Object> comDetails = instance.getStatusInfo().getDetails();
        if (MapUtils.isEmpty(comDetails)) {
            return "";
        }
        try {
            for (Map.Entry<String, Object> entry : comDetails.entrySet()) {
                Map comDetail = (Map<String, Object>) entry.getValue();
                Object state = comDetail.get("status");
                if ("DOWN".equals(state)) {
                    downComponents.add(entry.getKey());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "服务异常,请及时处理！";
        }
        if (CollectionUtils.isEmpty(downComponents)) {
            return "服务异常,请及时处理！";
        }
        return downComponents.stream().collect(Collectors.joining("、")) + "组件不可用！";
    }

}

